const app = getApp();

Page({
  data: {
    doctors: [],
    showAppointmentModal: false,
    selectedDoctor: null,
    appointmentDate: new Date().toISOString().slice(0, 10),
    appointmentTime: '10:00'
  },

  onShow() {
    this.loadDoctors();
  },

  loadDoctors() {
    app.request('/api/doctors').then(res => {
      this.setData({ doctors: res });
    }).catch(err => {
      wx.showToast({ title: '加载医生失败', icon: 'none' });
    });
  },

  showModal(e) {
    const doctor = e.currentTarget.dataset.doctor;
    this.setData({ 
      showAppointmentModal: true, 
      selectedDoctor: doctor 
    });
  },
  
  closeModal() {
    this.setData({ showAppointmentModal: false });
  },

  bindDateChange(e) { this.setData({ appointmentDate: e.detail.value }); },
  bindTimeChange(e) { this.setData({ appointmentTime: e.detail.value }); },
  
  submitAppointment() {
    const { selectedDoctor, appointmentDate, appointmentTime } = this.data;
    const userId = app.globalData.userInfo.id;
    const fullTime = `${appointmentDate} ${appointmentTime}:00`; 

    wx.showLoading({ title: '预约中...' });

    app.request('/api/appointment', 'POST', {
      userId: userId,
      doctorId: selectedDoctor.id,
      appointmentTime: fullTime
    }).then(res => {
      wx.hideLoading();
      wx.showToast({ title: res.message, icon: 'success' });
      this.closeModal();
      // 后端已通过 WebSocket 自动通知了医生端
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({ title: err, icon: 'none' });
    });
  }
});